package cn.wwk.notification.search.service.iml;

import cn.wwk.notification.common.result.CodeMsg;
import cn.wwk.notification.common.result.Result;
import cn.wwk.notification.search.doc.IndexParams;
import cn.wwk.notification.search.service.CommonIndexService;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author wwk
 */
@Service
public class CommonIndexServiceImpl implements CommonIndexService {


    @Resource
    private RestHighLevelClient client;


    /**
     * 通用创建索引库操作，
     *
     * @param index
     */
    @Override
    public Result createIndex(IndexParams index) throws IOException {
        //1.创建索引库
        CreateIndexRequest request = new CreateIndexRequest(index.getIndexName());
        //2.填入DSL语句和格式
        request.source(index.getDSL(), XContentType.JSON);
        //3.发送创建请求
        client.indices().create(request, RequestOptions.DEFAULT);

        return Result.success(CodeMsg.SUCCESS);
    }

    /**
     * Delete index.
     *
     * @param indexName the index name
     * @throws IOException the io exception
     */
    @Override
    public void deleteIndex(String indexName) throws IOException {
        // 1.创建Request对象
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        // 2.发送请求
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

    /**
     * Exists index.
     *
     * @param indexName the index name
     * @throws IOException the io exception
     */
    @Override
    public boolean existsIndex(String indexName) throws IOException {
        // 1.创建Request对象
        GetIndexRequest request = new GetIndexRequest(indexName);
        // 2.发送请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        // 3.输出
        System.err.println(exists ? "索引库已经存在！" : "索引库不存在！");
        return exists;
    }
}
